import onload from "./utils/onload";
import tracker from "./utils/tracker";

// 白屏检测
export function blankScreen() {
  // 定义需要检查的包裹元素
  let wrapperElements = ["html", "body", "#container", ".content"];
  // 记录空白点数
  let emptyPoints = 0;

  // 获取元素的选择器
  function getSelector(element) {
    if (element?.id) {
      return "#" + id;
    } else if (element?.className) {
      return (
        "." +
        element.className
          .split(" ")
          .filter((item) => !!item)
          .join(".")
      );
    } else {
      return element?.nodeName.toLowerCase();
    }
  }

  // 判断元素是否为包裹元素
  function isWrapper(element) {
    let selector = getSelector(element);
    if (wrapperElements.indexOf(selector) !== -1) {
      emptyPoints++;
    }
  }

  onload(function () {
    // 检查屏幕的点，分别为横向和纵向的点
    for (let i = 1; i <= 9; i++) {
      let xElements = document.elementsFromPoint(
        (window.innerWidth * i) / 10,
        window.innerHeight / 2
      );
      let yElements = document.elementsFromPoint(
        window.innerWidth / 2,
        (window.innerHeight * i) / 10
      );

      isWrapper(xElements[0]);
      isWrapper(yElements[0]);
    }

    // 如果空白点数超过16个，表示屏幕为空白
    if (emptyPoints > 16) {
      let centerElements = document.elementsFromPoint(
        window.innerWidth / 2,
        window.innerHeight / 2
      );
      tracker.send({
        kind: "stability",
        type: "blank",
        emptyPoints,
        screen: window.screen.width + "*" + window.screen.height,
        viewPoint: window.innerWidth + "*" + window.innerHeight,
        selector: getSelector(centerElements[0]),
      });
    }
  });
}
